package org.fhawk.tinyspring.util;

import org.apache.commons.lang.StringUtils;
import org.fhawk.tinyspring.Constant;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Created by tuo on 8/11/2016.
 * 用于加载properties文件
 */
public class PropsUtil {
    private PropsUtil() {
    }

    /**
     * 加载properties
     *
     * @param propsPath 配置文件
     * @return bundle
     */
    public static ResourceBundle loadProps(String propsPath) {
        if (StringUtils.isEmpty(propsPath)) {
            throw new IllegalArgumentException();
        }
        String env = System.getenv(Constant.PROFILE_ENV);
        if (!StringUtils.isEmpty(env)) {
            propsPath = propsPath + "-" + env;
        }
        return ResourceBundle.getBundle(propsPath);
    }

    /**
     * 加载properties文件为map
     *
     * @param propsPath
     * @return
     */
    public static Map<String, String> loadPropsToMap(String propsPath) {
        Map<String, String> map = new HashMap<>();
        ResourceBundle bundle = loadProps(propsPath);
        for (String key : bundle.keySet()) {
            map.put(key, bundle.getString(key));
        }
        return map;
    }

    public static Map<String, String> getMap(String propPath, String prefix) {
        Map<String, String> map = new HashMap<>();
        ResourceBundle bundle = loadProps(propPath);
        bundle.keySet().stream().filter(name -> name.startsWith(prefix)).forEach(name -> map.put(name, bundle.getString(name)));
        return map;
    }

}
